import cv2
import datetime
import time

# 设置摄像头索引，通常为0表示默认摄像头
camera_index = 0

# 打开摄像头
cap = cv2.VideoCapture(camera_index)

# 检查摄像头是否成功打开
if not cap.isOpened():
    print("Error: Could not open camera.")
    exit()

# 获取摄像头的帧率和分辨率
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(width,height)

# 每半个小时的间隔
interval_seconds = 10

# 记录开始时间
start_time = time.time()

# 创建视频写入对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 使用 mp4v 编码器
output_file = f"recorded_video_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
out = cv2.VideoWriter(output_file, fourcc, fps, (width, height), isColor=True)

# 设置视频压缩质量（0-100）
out.set(cv2.VIDEOWRITER_PROP_QUALITY, 50)  # 调整这个值以控制质量

try:
    while True:
        ret, frame = cap.read()

        if not ret:
            print("Error: Could not read frame.")
            break

        # 显示当前帧
        cv2.imshow("Camera Feed", frame)

        # 将当前帧写入视频文件
        out.write(frame)

        # 检查是否到达存储间隔
        elapsed_time = time.time() - start_time
        if elapsed_time >= interval_seconds:
            # 关闭当前视频写入对象
            out.release()

            # 生成新的文件名
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = f"recorded_video_{timestamp}.mp4"

            # 创建新的视频写入对象
            out = cv2.VideoWriter(output_file, fourcc, fps, (width, height))

            # 设置新的视频压缩质量
            out.set(cv2.VIDEOWRITER_PROP_QUALITY, 20)

            # 重置开始时间
            start_time = time.time()

        # 检查是否按下 'q' 键退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

except Exception as e:
    print(f"Error: {e}")

finally:
    # 释放资源
    cap.release()
    out.release()
    cv2.destroyAllWindows()




